//
//  PlayMovieVC.m
//  Daily
//
//  Created by dlios on 15/8/22.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "PlayMovieVC.h"
#define PLAYWIDTH self.player.view.frame.size.height
#define PLAYHEIGHT self.player.view.frame.size.width
#import "VideoModel.h"
typedef NS_ENUM(NSInteger, BoardType) {
    BoardHidden,
    BoardNoHidden
};

@interface PlayMovieVC ()

// 控制面板是否出现
@property (nonatomic, assign) BoardType boardType;
@property(nonatomic, strong)MBProgressHUD *hud;

@property(nonatomic, strong)MPMoviePlayerController *player;

@property(nonatomic, strong)UIView *downPanel;
@property(nonatomic, strong)UIView *upPanel;
@property(nonatomic, strong)UISlider *slider;
@property(nonatomic, strong)UILabel *currentTime;
@property(nonatomic, strong)UILabel *chiefTime;
@property(nonatomic, strong)UILabel *titleLabel;

@property(nonatomic, strong)UIButton *playOrStop;
@property(nonatomic, strong)UIButton *back;
@property(nonatomic, strong)UIButton *nextMovie;
@property(nonatomic, strong)UIButton *lastMovie;

@property(nonatomic, strong)NSTimer *timer;

@property(nonatomic, assign)NSInteger daley;

@property(nonatomic, strong)UIImageView *endView;
@end

@implementation PlayMovieVC

- (void)viewDidDisappear:(BOOL)animated
{
    [_timer invalidate];
    _timer = nil;
    [self.player stop];
//    [_slider removeObserver:self forKeyPath:@"value"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.movieArr = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.boardType = BoardNoHidden;
    [self createPlayer];
    [self createDownPanel];
    [self showMBPrograssHUD];
    [self addTap];
    [self addNotification];
    [self.player play];
}
#pragma mark -
#pragma mark 隐藏状态栏
- (BOOL)prefersStatusBarHidden
{
    return YES;
}
- (void)createPlayer
{
    VideoModel *model = self.movieArr[self.index];
    self.player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:model.playUrl]];
    self.player.view.frame = CGRectMake(0, 0, HEIGHT, WIDTH);
    self.player.view.transform = CGAffineTransformMakeRotation( -M_PI_2);
    self.player.view.center = CGPointMake(WIDTH / 2, HEIGHT / 2);
    self.player.controlStyle = MPMovieControlStyleNone;
    self.player.shouldAutoplay = YES;
    [self.view addSubview:self.player.view];

}
#pragma mark -
#pragma mark 创建底部控制面板
- (void)createDownPanel
{
    self.downPanel = [[UIView alloc] initWithFrame:CGRectMake(0, PLAYHEIGHT - 40, PLAYWIDTH, 40)];
    self.downPanel.backgroundColor = [UIColor clearColor];
    [self.player.view addSubview:self.downPanel];
    
    self.upPanel = [[UIView alloc] initWithFrame:CGRectMake(0, 0, PLAYWIDTH, 40)];
    self.upPanel.backgroundColor = [UIColor clearColor];
    [self.player.view addSubview:self.upPanel];
    
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(55, 17, PLAYWIDTH - 110, 8)];
    self.slider.minimumTrackTintColor = [UIColor whiteColor];
    self.slider.maximumTrackTintColor = [UIColor colorWithWhite:0.5 alpha:0.5];
    [self.slider setThumbImage:[UIImage imageNamed:@"yuan"] forState:UIControlStateNormal];
//    // slider拖动结束后触发事件.默认是YES,一直触发.
//    self.slider.continuous = NO;
    [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [self.slider addTarget:self action:@selector(sliderTouchBegin) forControlEvents:UIControlEventTouchDown];
    [self.slider addTarget:self action:@selector(sliderTouchUp) forControlEvents:UIControlEventTouchUpInside];
    [self.slider addTarget:self action:@selector(sliderTouchUp) forControlEvents:UIControlEventTouchUpOutside];
//    [self.slider addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionNew context:nil];
    [self.downPanel addSubview:self.slider];
    
    self.currentTime = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 55, 40)];
    self.currentTime.backgroundColor = [UIColor clearColor];
    self.currentTime.textColor = [UIColor whiteColor];
    self.currentTime.textAlignment = 2;
    self.currentTime.font = [UIFont systemFontOfSize:12];
    self.currentTime.text = @"00:00";
    [self.downPanel addSubview:self.currentTime];
    
    self.chiefTime = [[UILabel alloc] initWithFrame:CGRectMake(PLAYWIDTH - 55, 0, 55, 40)];
    self.chiefTime.backgroundColor = [UIColor clearColor];
    self.chiefTime.textColor = [UIColor whiteColor];
    self.chiefTime.font = [UIFont systemFontOfSize:12];
    self.chiefTime.text = @"00:00";
    [self.downPanel addSubview:self.chiefTime];

    self.playOrStop = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playOrStop.frame = CGRectMake(0, 0, 50, 50);
    self.playOrStop.center = CGPointMake(PLAYWIDTH / 2, PLAYHEIGHT / 2);
    self.playOrStop.backgroundColor = [UIColor clearColor];
    [self.playOrStop setImage:[UIImage imageNamed:@"playMV"] forState:UIControlStateNormal];
    [self.playOrStop addTarget:self action:@selector(playOrStopAction:) forControlEvents:UIControlEventTouchUpInside];
    self.playOrStop.tag = 1;
    [self.player.view addSubview:self.playOrStop];
    
    self.nextMovie = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextMovie.frame = CGRectMake(0, 0, 40, 40);
    self.nextMovie.center = CGPointMake(PLAYWIDTH - 30, PLAYHEIGHT / 2);
    [self.nextMovie setImage:[UIImage imageNamed:@"next"] forState:UIControlStateNormal];
    [self.nextMovie addTarget:self action:@selector(playNextMovie:) forControlEvents:UIControlEventTouchUpInside];
    [self.player.view addSubview:self.nextMovie];
    
    self.lastMovie = [UIButton buttonWithType:UIButtonTypeCustom];
    self.lastMovie.frame = CGRectMake(0, 0, 40, 40);
    self.lastMovie.center = CGPointMake(30, PLAYHEIGHT / 2);
    [self.lastMovie setImage:[UIImage imageNamed:@"last"] forState:UIControlStateNormal];
    [self.lastMovie addTarget:self action:@selector(playLastMovie:) forControlEvents:UIControlEventTouchUpInside];
    [self.player.view addSubview:self.lastMovie];
    
    self.back = [UIButton buttonWithType:UIButtonTypeCustom];
    self.back.frame = CGRectMake(8, 5, 40, 40);
    [self.back setImage:[UIImage imageNamed:@"goback"] forState:UIControlStateNormal];
    [self.back addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.upPanel addSubview:self.back];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 5, 300, 40)];
//    [self.titleLabel sizeToFit];
//    self.titleLabel.numberOfLines = 1;
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont systemFontOfSize:15];
    self.titleLabel.backgroundColor = [UIColor clearColor];
    VideoModel *model = self.movieArr[self.index];
    self.titleLabel.text = model.title;
    [self.upPanel addSubview:self.titleLabel];
}

#pragma mark -
#pragma mark 滑条
- (void)sliderAction:(UISlider *)slider
{
    self.currentTime.text = [self changeTimeWithSeconds:slider.value];
}
- (void)sliderTouchBegin
{
    [self.player pause];
    [self.timer setFireDate:[NSDate distantFuture]];

}
- (void)sliderTouchUp
{
    if (self.player.duration > 0) {
        self.player.currentPlaybackTime = self.slider.value;
        self.currentTime.text = [self changeTimeWithSeconds:self.player.currentPlaybackTime];
        [self.timer setFireDate:[NSDate distantPast]];
        [self.player play];
    }else{
        self.slider.value = 0;
    }
}
////在slider正在拖动时候执行
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
//{
////    [self.player pause];
////    [self.timer setFireDate:[NSDate distantFuture]];
//}
#pragma mark -
#pragma mark 下一首
- (void)playNextMovie:(UIButton *)button
{
    [self.hud hide:YES];
    self.playOrStop.hidden = NO;
    if (self.index == self.movieArr.count - 1) {
        NSLog(@"========");
    }else{
        [self.endView removeFromSuperview];
        
        [self showMBPrograssHUD];
        
        [self.player stop];
        self.index += 1;
        VideoModel *model = self.movieArr[self.index];
        self.titleLabel.text = model.title;
        self.player.contentURL = [NSURL URLWithString:model.playUrl];
        [self.player play];
    }
}
#pragma mark -
#pragma mark 上一首
- (void)playLastMovie:(UIButton *)button
{
    [self.hud hide:YES];
    self.playOrStop.hidden = NO;
    if (self.index == 0) {
        NSLog(@"========");
    }else{
        [self.player stop];
        self.index -= 1;
        VideoModel *model = self.movieArr[self.index];
        self.titleLabel.text = model.title;
        self.player.contentURL = [NSURL URLWithString:model.playUrl];
        [self.player play];
    }
}
#pragma mark -
#pragma mark 返回
- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark -
#pragma mark -播放
- (void)playOrStopAction:(UIButton *)button
{
    if (self.playOrStop.tag == 1) {
        [self.player pause];
        self.playOrStop.tag = 0;
    }else if (self.playOrStop.tag == 0) {
        [self.player play];
        self.playOrStop.tag = 1;
    }
}
#pragma mark -
#pragma mark 手势
- (void)addTap
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.playOrStop addGestureRecognizer:tap];
    [self.player.view addGestureRecognizer:tap];
    [[self.player.view.subviews firstObject] addGestureRecognizer:tap];
}
- (void)tapAction
{
    if (self.boardType == BoardNoHidden) {
        [UIView animateWithDuration:0.5 animations:^{
            
            self.downPanel.frame = CGRectMake(0, PLAYHEIGHT, PLAYWIDTH, 40);
            self.upPanel.frame = CGRectMake(0, -40, PLAYWIDTH, 40);
            self.playOrStop.alpha = 0;
            self.playOrStop.userInteractionEnabled = NO;
            self.nextMovie.center = CGPointMake(PLAYWIDTH + 10, PLAYHEIGHT / 2);
            self.lastMovie.center = CGPointMake(-40, PLAYHEIGHT / 2);
            self.boardType = BoardHidden;
        }];
    }
    
    else
    {[UIView animateWithDuration:0.5 animations:^{
        
        self.downPanel.frame = CGRectMake(0, PLAYHEIGHT - 40, PLAYWIDTH, 40);
        self.upPanel.frame = CGRectMake(0, 0, PLAYWIDTH, 40);
        self.playOrStop.alpha = 1;
        self.playOrStop.userInteractionEnabled = YES;
        self.nextMovie.center = CGPointMake(PLAYWIDTH - 30, PLAYHEIGHT / 2);
        self.lastMovie.center = CGPointMake(30, PLAYHEIGHT / 2);
        self.boardType = BoardNoHidden;
    }];
    }
}

#pragma mark -
#pragma mark 添加监听
- (void)addNotification
{
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    //播放状态发生改变
    [notification addObserver:self selector:@selector(mediaPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.player];
    //播放已经完成
    [notification addObserver:self selector:@selector(mediaPlaybackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.player];
    //加载状态发生改变
    [notification addObserver:self selector:@selector(mediaPlayerLoadStateChange:) name:MPMoviePlayerLoadStateDidChangeNotification object:self.player];
    //获取视频总长度后, 走这个方法
    [notification addObserver:self selector:@selector(mediaplayDurationAvailable:) name:MPMovieDurationAvailableNotification object:self.player];
}
//播放状态发生改变
- (void)mediaPlaybackStateChange:(NSNotificationCenter *)notification
{
    switch (self.player.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"正在播放");
            [self.playOrStop setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停播放");
            [self.playOrStop setImage:[UIImage imageNamed:@"playMV"] forState:UIControlStateNormal];
            self.playOrStop.tag = 0;
            break;
        case MPMoviePlaybackStateInterrupted:
            NSLog(@"中断播放");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"停止播放");
            break;
        case MPMoviePlaybackStateSeekingBackward:
            NSLog(@"向后播放");
            break;
        case MPMoviePlaybackStateSeekingForward:
            NSLog(@"向前播放");
            break;
        default:
            break;
    }
}
//播放已经完成
- (void)mediaPlaybackDidFinish:(NSNotificationCenter *)notification
{
    NSLog(@"播放完成");
    if (self.slider.value >= self.slider.maximumValue - 5) {
        
        [self createEndView];
    }
}
#pragma mark -
#pragma mark 结束界面
- (void)createEndView
{
    VideoModel *model = self.movieArr[self.index];
    self.endView = [[UIImageView alloc] initWithFrame:self.player.view.bounds];
    
    NSString *name = @"gif.gif";
    NSString *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    UIImage *image = [UIImage sd_animatedGIFWithData:imageData];
   
    [self.endView sd_setImageWithURL:[NSURL URLWithString:model.coverForFeed] placeholderImage:image];
    [self.player.view addSubview:self.endView];
    
    UIView *blackView = [[UIView alloc] initWithFrame:self.player.view.bounds];
    blackView.backgroundColor =[UIColor blackColor];
    blackView.alpha = 0.5;
    [self.endView addSubview:blackView];
    
    self.endView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backAction)];
    [blackView addGestureRecognizer:tap];
    
    UIImageView *backView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 30, 30, 30)];
    backView.center = CGPointMake(PLAYWIDTH / 2, PLAYHEIGHT / 2 + 40);
    backView.image = [UIImage imageNamed:@"iconfont-x"];
    backView.userInteractionEnabled = YES;
    [self.endView addSubview:backView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    titleLabel.center = CGPointMake(PLAYWIDTH / 2, PLAYHEIGHT / 2 - 50);
    titleLabel.text = model.title;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.endView addSubview:titleLabel];
    
    UIButton *nextBu = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [nextBu setImage:[UIImage imageNamed:@"iconfont-ttpodicon"] forState:UIControlStateNormal];
    nextBu.center = CGPointMake(PLAYWIDTH - 50, PLAYHEIGHT / 2);
    [nextBu addTarget:self action:@selector(playNextMovie:) forControlEvents:UIControlEventTouchUpInside];
    [self.endView addSubview:nextBu];
    
}
//加载状态发生改变
- (void)mediaPlayerLoadStateChange:(NSNotificationCenter *)notification
{
    switch (self.player.loadState) {
        case MPMovieLoadStateUnknown:
            
            break;
        case MPMovieLoadStatePlayable:
            NSLog(@"加载状态:可以播放");
            [self.hud hide:YES];
            self.playOrStop.hidden = NO;
            break;
        case MPMovieLoadStatePlaythroughOK:
            NSLog(@"加载状态:将自动播放");
            [self.hud hide:YES];
            self.playOrStop.hidden = NO;
            break;
        case MPMovieLoadStateStalled:
            NSLog(@"加载状态:停滞");
            break;
        default:
            break;
    }
}
//获取视频总长度后, 走这个方法
- (void)mediaplayDurationAvailable:(NSNotificationCenter *)notification
{
    self.chiefTime.text = [self changeTimeWithSeconds:self.player.duration];
    self.slider.maximumValue = self.player.duration;
    [self.timer setFireDate:[NSDate distantPast]];
    NSLog(@"播放时长%g", self.player.duration);
}
//时间转换
- (NSString *)changeTimeWithSeconds:(CGFloat)seconds
{
    NSInteger hour = floor(seconds / 3600);
    NSInteger minutes = floor((seconds - hour * 3600) / 60);
    NSInteger s = seconds - hour * 3600 - minutes * 60;
    NSString *time = @"";
    if (hour == 0) {
        time = [NSString stringWithFormat:@"%.2ld:%.2ld", (long)minutes, (long)s];
    }else{
        time = [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld", (long)hour, (long)minutes, (long)s];
    }
    return time;
}
#pragma mark - 刷新时间
//timer  get方法
- (NSTimer *)timer
{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];
        [_timer setFireDate:[NSDate distantFuture]];
    }
    return _timer;
}
- (void)timeAction:(NSTimer *)time
{
    if (self.player.duration > 0) {
        self.currentTime.text = [self changeTimeWithSeconds:self.player.currentPlaybackTime];
        [self.slider setValue:self.player.currentPlaybackTime animated:YES];
    }
    //自动隐藏操作栏
    if (self.boardType == BoardNoHidden) {
        self.daley++;
        if (self.daley == 5) {
            [self tapAction];
        }
    }else{
        self.daley = 0;
    }

}
#pragma mark -
#pragma mark 显示小菊花
- (void)showMBPrograssHUD
{
    self.playOrStop.hidden = YES;
    //小菊花
    self.hud = [[MBProgressHUD alloc] init];
    self.hud.color = [UIColor clearColor];
    self.hud.removeFromSuperViewOnHide = YES;
    [self.player.view addSubview:self.hud];
    [self.hud show:YES];
    [self.player.view insertSubview:self.hud belowSubview:self.upPanel];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
